package leetcode.editor.temp;

import java.util.*;

public class blockGame {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        List<int[][]> list = new ArrayList<>();
        List<int[]> Bx = new ArrayList<>();
        int T = sc.nextInt(); // T测试组数
        while (--T>=0){
            int n = sc.nextInt(), m = sc.nextInt(), k = sc.nextInt();// 行数 列数 方块种类数
            int[][] arr = new int[n][m];
            for (int i = 0; i < n; i++){
                for (int j = 0; j < n; j++) {
                    arr[i][j] = sc.nextInt();
                }
            }
            list.add(arr);
            int[] b = new int[k + 1];
            b[0] = -1;
            for (int i = 1; i < k + 1; i++){
                b[i] = sc.nextInt();
            }
            Bx.add(b);
        }
        // 初始化步骤完成
        // 遍历list
        for (int i = 0; i < list.size(); i++){
            int[][] arr = list.get(i);
            int[] B = Bx.get(i);
            // 判断方块类型, 是否施加重力.
            for (int a = arr.length-1; a >= 0; a--){
                for (int b = arr[0].length - 1; b >= 0; b--){
                    int t = arr[a][b];
                    int x = a + 1;
                    if (B[t] == 1){
                        // 受重力影响, 该数下移到不为0的位置
                        while (x < arr.length && arr[x][b]==0){
                            x++;
                        }
                        arr[a][b] = 0;
                        arr[x-1][b] = t;
                    }
                }
            }
            for (int a = 0; a < arr.length; a++){
                for (int b = 0; b < arr[0].length; b++){
                    System.out.print(arr[a][b]+" ");
                }
                System.out.println();
            }
        }
    }
}